//
//  DiscoveryViewController.m
//  EverydayDemo
//
//  Created by qianfeng01 on 15-7-17.
//  Copyright (c) 2015年 qianfeng01. All rights reserved.
//

#import "DiscoveryViewController.h"
#import "DiscoveryCell.h"
#import "HomePageModel.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "DetailViewController.h"
#import "WMPageController.h"
#import "ThingViewController.h"
#import "TravleViewController.h"
#import "HomePageModel.h"
#import "FoodViewController.h"
#import "FashionViewController.h"
@interface DiscoveryViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *ListdataArr;
@property(nonatomic,strong)NSMutableArray *scrollDataArr;
@property(nonatomic,strong)AFHTTPRequestOperationManager *manager;
@property(nonatomic,strong)UIView *Headview;
@property(nonatomic,strong)NSMutableArray *imagesArr;
@property(nonatomic,strong)NSMutableArray *titleArr;
@end

@implementation DiscoveryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.ListdataArr=[[NSMutableArray alloc]init];
    self.scrollDataArr=[[NSMutableArray alloc]init];
    self.imagesArr=[[NSMutableArray alloc]init];
    self.titleArr=[[NSMutableArray alloc]init];
        [self creatTableView];
   
    [self downloadTableViewData];
    [self downHeaderViewData];
    [self downCategoryData];
    [self creatRefreshView];
}

-(void)creatLabel
{
    for (int i=0; i<5; i++) {
        UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.cornerRadius=(kScreenSize.width-80)/10;
        button.frame=CGRectMake(i*kScreenSize.width/5+8,(kScreenSize.height/3)+10, (kScreenSize.width-80)/5, (kScreenSize.width-80)/5);
        button.tag=100+i;
     
        
        switch (i) {
            case 0:
            {
                  button.backgroundColor=[UIColor colorWithRed:100/255 green:300/255 blue:100/255 alpha:0.5];
            }
                break;
            case 1:
            {
               button.backgroundColor=[UIColor colorWithRed:200/255 green:100/255 blue:300/255 alpha:0.5];
            }
                break;
            case 2:
            {
                button.backgroundColor=[UIColor colorWithRed:300/255 green:100/255 blue:100/255 alpha:0.5];
            }
                break;
            case 3:
            {
                button.backgroundColor=[UIColor colorWithRed:10/255 green:300/255 blue:300/255 alpha:0.5];
            }
                break;
            case 4:
            {
                button.backgroundColor=[UIColor colorWithRed:300/255 green:100/255 blue:300/255 alpha:0.5];
            }
                break;
            default:
                break;
        }
        [button sd_setBackgroundImageWithURL:[NSURL URLWithString:self.imagesArr[i]] forState:UIControlStateNormal];
     
        UILabel *categoryLabel=[[UILabel alloc]initWithFrame:CGRectMake(i*kScreenSize.width/5+8, (kScreenSize.height/3)+15+(kScreenSize.width-80)/5, (kScreenSize.width-80)/5, 20)];
        categoryLabel.text=self.titleArr[i];
        categoryLabel.textAlignment=NSTextAlignmentCenter;
        categoryLabel.font=[UIFont boldSystemFontOfSize:14.0];
        [self.Headview addSubview:button];
        [self.Headview addSubview:categoryLabel];
       
    }
    
}
-(void)btnClick:(UIButton *)button
{
    NSArray*categoryArr=@[@"FashionViewController",@"FoodViewController",@"HomeViewController",@"TravleViewController",@"ThingViewController"];
    Class cls = NSClassFromString(categoryArr[button.tag-100]);
    UIViewController *vc = [[cls alloc]init];
    vc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:vc animated:YES];
    

}
-(void)creatScrollView
{
    UIScrollView *scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenSize.width,kScreenSize.height/3)];
    for (int i=0; i<self.scrollDataArr.count; i++) {
        HomePageModel *model=self.scrollDataArr[i];
        UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(i* kScreenSize.width,0,kScreenSize.width, kScreenSize.height/3)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:model.imageUrl]placeholderImage:[UIImage imageNamed:@"default.png"]];
        [scrollView addSubview:imageView];
        UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake( i*kScreenSize.width,(kScreenSize.height/3)-30, kScreenSize.width-80, 30)];
        titleLabel.text=model.title;
        titleLabel.textColor=[UIColor whiteColor];
        titleLabel.font=[UIFont boldSystemFontOfSize:14.0];
        [scrollView addSubview:titleLabel];
        UILabel *countLabel=[[UILabel alloc]initWithFrame:CGRectMake(i*kScreenSize.width+kScreenSize.width-50,(kScreenSize.height/3)-30, kScreenSize.width-80, 30)];
        countLabel.text=[NSString stringWithFormat:@"%d/%ld",i+1,(unsigned long)self.scrollDataArr.count];
        countLabel.textColor=[UIColor yellowColor];
        [scrollView addSubview:countLabel];
        scrollView.showsHorizontalScrollIndicator=NO;
    }
    UITapGestureRecognizer *tap= [[UITapGestureRecognizer alloc] init];
    [tap addTarget:self action:@selector(tap:)];
    [scrollView addGestureRecognizer:tap];
    scrollView.pagingEnabled=YES;
    scrollView.contentSize=CGSizeMake(self.scrollDataArr.count*kScreenSize.width, kScreenSize.height/3);
    [self.Headview addSubview:scrollView];
}
-(void)tap:(UITapGestureRecognizer *)tap
{
    DetailViewController *cnv=[[DetailViewController alloc]init];
    UIScrollView *view=(UIScrollView *)tap.view;
    int a=view.contentOffset.x/kScreenSize.width;
    HomePageModel *model=self.scrollDataArr[a];
    cnv.url=model.url;
    cnv.articleId=model.articleId;
    cnv.imageUrl=model.imageUrl;
    cnv.Artitle=model.title;
    cnv.categryName=model.categryName;
    cnv.authorName=model.authorName;
    cnv.readCount=model.readCount;
    cnv.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:cnv animated:YES];
}
-(void)downloadTableViewData
{
    self.limit=10;
    [self downDataWithUrl:[NSString stringWithFormat:kDiscoveryUrl,(long)self.limit] isRefresh:NO];
}
-(void)downHeaderViewData
{
    [self downDataWithUrl:kScrollViewUrl isRefresh:NO];
}
-(void)downCategoryData
{
    [self downDataWithUrl:kCategoryUrl isRefresh:NO];
}
-(void)creatRefreshView
{
    __weak typeof (self) weakSelf = self;
    [weakSelf.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing=YES;
        weakSelf.limit=10;
        [weakSelf downDataWithUrl:[NSString stringWithFormat:kDiscoveryUrl,(long)weakSelf.limit] isRefresh:YES];
        
    }];
    [weakSelf.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class]  beginRefresh:^{
        if (weakSelf.isLoadMore) {
            return;
        }
        weakSelf.isLoadMore=YES;
        weakSelf.limit+=10;
        [weakSelf downDataWithUrl:[NSString stringWithFormat:kDiscoveryUrl,(long)weakSelf.limit] isRefresh:YES];
    }];
}
- (void)endRefreshing {
    if (self.isRefreshing) {
        self.isRefreshing = NO;//标记刷新结束
        //正在刷新 就结束刷新
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultNone];
    }
    if (self.isLoadMore) {
        self.isLoadMore = NO;
        [self.tableView footerEndRefreshing];
    }
}
-(void)downDataWithUrl:(NSString *)url  isRefresh:(BOOL)isReFresh
{
    
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    __weak typeof (self) weakSelf=self;
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            if ([url isEqualToString:kScrollViewUrl]||[url isEqualToString:kCategoryUrl]) {
                
            }else{
                [weakSelf.ListdataArr removeAllObjects];
            }
           
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *array=dict[@"result"];
            for (NSDictionary *dedict in array) {
                if ([url isEqualToString:kCategoryUrl]) {
                   [weakSelf.imagesArr addObject:dedict[@"category"][0][@"categoryGroup"][@"icon"]];
                    [weakSelf.titleArr addObject:dedict[@"category"][0][@"categoryGroup"][@"name"]];
                }else{
                HomePageModel *model=[[HomePageModel alloc]init];
                [model setValue:dedict];
                    if ([url isEqualToString:kScrollViewUrl]) {
                        [weakSelf.scrollDataArr addObject:model];
                    }else{
                  
                 [weakSelf.ListdataArr addObject:model];
                    }
                }
            }
         
        }
        if ([url isEqualToString:kCategoryUrl]) {
            [weakSelf creatLabel];
        }else if ([url isEqualToString:kScrollViewUrl]) {
            [weakSelf creatScrollView];
        } else{
            [weakSelf.tableView reloadData];
        }

       [weakSelf endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载数据错误");
    }];
}
-(void)creatTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,-44, kScreenSize.width, kScreenSize.height+44) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight=109;
    [self.tableView registerNib:[UINib nibWithNibName:@"DiscoveryCell" bundle:nil] forCellReuseIdentifier:@"DiscoveryCell"];
     self.Headview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height/2)];
    self.tableView.tableHeaderView=self.Headview;
    [self.view addSubview:self.tableView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.ListdataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DiscoveryCell *cell=[tableView dequeueReusableCellWithIdentifier:@"DiscoveryCell" forIndexPath:indexPath];
    HomePageModel *model=self.ListdataArr[indexPath.row];
    [cell setData:model];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *cnv=[[DetailViewController alloc]init];
    HomePageModel *model=self.ListdataArr[indexPath.row];
    cnv.url=model.url;
    cnv.articleId=model.articleId;
    cnv.imageUrl=model.imageUrl;
    cnv.Artitle=model.title;
    cnv.categryName=model.categryName;
    cnv.authorName=model.authorName;
    cnv.readCount=model.readCount;
    cnv.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:cnv animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
